<?php

namespace app\api\controller;

use app\common\controller\BasicApi;
use app\common\model\CourseModel;
use app\common\model\UserModel;
use app\common\model\AssociationModel;
use app\common\model\UserSummaryModel;

class UserSummary extends BasicApi
{
    protected $member;
    protected $openid;

    public function _initialize()
    {
        parent::_initialize();
        $this->openid = isset($this->header['token'])?$this->header['token']:'';
    }

    /**
     * 提交期末资料
     */
    public function summary()
    {
        $course_id = $this->request->post('course_id');
        $info = UserSummaryModel::where(['openid'=>$this->openid, 'course_id' => $course_id])->find();
        if($info) {
            $info->file_url = $this->request->post('file_url');
            $result = $info->save();

        } else {
            $course_info = CourseModel::get($course_id);
            $user_info = $this->getMember();
            $data = array(
                'user_id' => $user_info['id'],
                'nickname' => $user_info['nickname'],
                'realname' => $user_info['realname'],
                'openid' => $user_info['openid'],
                'school_id' => $course_info['school_id'],
                'course_id' => $course_id,
                'course_name' => $course_info['name'],
                'file_url' => $this->request->post('file_url'),
                'create_time' => date('Y-m-d H:i:s'),
            );
            $result = UserSummaryModel::create($data);
        }

        if($result){
            $this->success('操作成功',$result,200);
        }
        $this->error('操作异常，请重试');
    }

    /**
     * 获取期末资料
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSummary()
    {
        $course_id = $this->request->post('course_id');
        $info = UserSummaryModel::where(['openid'=>$this->openid, 'course_id' => $course_id])->find();
        $this->success('',$info,200);
    }

    /**
     * 获取会员信息
     */
    protected function getMember()
    {
        return UserModel::where(['openid'=>$this->openid])->find();
    }
}